package com.qzsoft.zhjd.server.socket.handler;

import java.net.InetSocketAddress;

import org.springframework.stereotype.Component;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName TcpEnvLoginHandler
 * @Description 客户端登录
 * @author linhuawei
 * @since 2022-01-12
 */
@Slf4j
@Sharable
@Component
public class TcpEnvLoginHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRegistered(final ChannelHandlerContext ctx) throws Exception {
        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        InetSocketAddress remoteAddress = socketChannel.remoteAddress();
        log.info("客户端登录：{}", remoteAddress.toString());
    }

    @Override
    public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        if (socketChannel.isShutdown()) {
            log.info("客户端离线：{}", socketChannel.remoteAddress().toString());
        }
    }

    @Override
    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        if (socketChannel.isShutdown()) {
            log.info("客户端异常：{}", socketChannel.remoteAddress().toString());
        }
    }

    @Override
    public void channelActive(final ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelActive();
    }

}
